package com.ygp.basic;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j(topic = "c.TestJoin2")
public class TestJoin4 {
    private static final int init = 10;
    public static void main(String[] args) {
        List<Integer> dataList = Arrays.asList(1, 3, 5);
        List<Integer> result = new ArrayList<>();

        List<CompletableFuture<Integer>> tasks = dataList.stream()
                .map(taskSupplier(result)).collect(Collectors.toList());
        CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).join();
        log.debug("主任务执行完毕,最后结果：" + result);
    }

    private static Function<Integer, CompletableFuture<Integer>> taskSupplier(List<Integer> result) {
        return index -> CompletableFuture.supplyAsync(() -> sum(index))
                .whenComplete((t, f) -> result.add(t));
    }

    private static int sum(int data) {
        log.debug("任务：" + data);
        return init + data;
    }

}
